/*
 * @Author: ARMCSKGT 1213955821@qq.com
 * @Date: 2023-10-14 15:14:58
 * @LastEditors: ARMCSKGT 1213955821@qq.com
 * @LastEditTime: 2023-10-14 17:34:55
 * @FilePath: /ARMCSKGT/Mysql/test1/main.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <iostream>
#include <string>
#include <mysql/mysql.h>

std::string host = "127.0.0.1";
std::string user = "armcskgt";
std::string passwd = "123456";
std::string db = "ZZ";
unsigned int port = 3306;


int main()
{
    //std::cout<<mysql_get_client_info()<<std::endl;
    MYSQL* my = mysql_init(nullptr);
    if(my == nullptr)
    {
        std::cerr<<"mysql init error"<<std::endl;
        return 1;
    }
    mysql_set_character_set(my, "utf8");
    if(mysql_real_connect(my,host.c_str(),user.c_str(),passwd.c_str(),db.c_str(),port,nullptr,0) == nullptr)
    {
        std::cerr<<"mysql connect error"<<std::endl;
        mysql_close(my);
        return 2;
    }

    // std::cout<<"mysql start success"<<std::endl;
    std::string line;
    // line.reserve(256);
    // while(true)
    // {
    //     std::cout<<">>> ";
    //     if(!std::getline(std::cin,line) || line == "quit") break;
    //     if(mysql_query(my,line.c_str()) != 0) std::cerr<<"mysql query error"<<std::endl;
    //     else std::cout<<"mysql query success"<<std::endl;
    // }
    // std::cout<<"Bye!"<<std::endl;
    
    //line = "insert into perple value (3,'王五')";
    //line = "delete from perple where id=2";
    //line = "update perple set id=2 where id=3";
    line = "select * from perple";
    if(mysql_query(my,line.c_str()) != 0) 
    {
        std::cerr<<"mysql query error"<<std::endl;
        mysql_close(my);
        return 3;
    }

    MYSQL_RES * res = mysql_store_result(my);
    if(res == nullptr)
    {
        std::cerr<<"mysql store result error"<<std::endl;
        mysql_close(my);
        return 4;
    }

    //行数
    my_ulonglong rownum = mysql_num_rows(res);

    //列数
    my_ulonglong colnum = mysql_num_fields(res);

    //std::cout<<"行数:"<<rownum<<" 列数:"<<colnum<<std::endl;

    //获取列信息(列头)
    MYSQL_FIELD * field = mysql_fetch_fields(res);
    for(int i = 0;i<colnum;++i)
    {
        std::cout<<field[i].name<<"\t";
    }
    std::cout<<"\n";

    //打印查询内容
    for(int i = 0;i<rownum;++i)
    {
        MYSQL_ROW mrow = mysql_fetch_row(res);
        for(int k = 0;k<colnum;++k)
            std::cout<<mrow[k]<<"\t";
            
        std::cout<<"\n";
    }

    mysql_free_result(res);
    mysql_close(my);
    return 0;
}